package com.liu.stockmarket.ui.self

import androidx.lifecycle.*
import com.liu.stockmarket.model.HoldingStockProfit
import com.liu.stockmarket.repository.database.StockRepository
import com.liu.stockmarket.repository.database.entity.StockEntity
import com.liu.stockmarket.repository.network.EasyMoneyRepository
import com.liu.stockmarket.utils.StockTransactionUtil
import com.liu.stockmarket.utils.diffToStockTransaction
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class SelfViewModel(
    private val stockRepository: StockRepository,
    private val easyMoneyRepository: EasyMoneyRepository
) : ViewModel() {

    val allSelf = stockRepository.allSelf.asLiveData()

    private val _nowPrices = MutableLiveData<List<SelfAdapter.Item>>()
    val nowPrices: LiveData<List<SelfAdapter.Item>> = _nowPrices

    private val _compositeIndex = MutableLiveData<List<SelfAdapter.Item>>()
    val compositeIndex: LiveData<List<SelfAdapter.Item>> = _compositeIndex

    fun queryNowPrice(list: List<StockEntity>) {
        viewModelScope.launch(Dispatchers.IO) {
//            val compositeIndex1 = easyMoneyRepository.getCompositeIndex()
//            _compositeIndex.postValue(compositeIndex1?.data?.diff?.diffToStockTransaction())
            val nowPrice =
                StockTransactionUtil.nowPrice(easyMoneyRepository, list, COMPOSITE_INDEX_SECIDS)

            // 指数
            val secids = COMPOSITE_INDEX_SECIDS.split(",").map {
                it.substring(2)
            }
            _compositeIndex.postValue(nowPrice.filter {
                secids.contains(it.code)
            })


            _nowPrices.postValue(nowPrice.filter {
                !secids.contains(it.code)
            })
        }
    }

    fun deleteSelf(selfId: Long) {
        viewModelScope.launch (Dispatchers.IO){
            stockRepository.deleteStock(selfId)
        }
    }




    companion object {
        /**
         * 指数代码（上证：1.000001,沪深300：1.000300,深证指数：0.399001,创业板指：0.399006）
         */
        const val COMPOSITE_INDEX_SECIDS = "1.000001,0.399001,1.000300,0.399006"
    }


    class SelfViewModeFactory(
        private val stockRepository: StockRepository,
        private val easyMoneyRepository: EasyMoneyRepository
    ) :
        ViewModelProvider.Factory {
        @SuppressWarnings("Unchecked")
        override fun <T : ViewModel?> create(modelClass: Class<T>): T {

            if (modelClass.isAssignableFrom(SelfViewModel::class.java)) {
                return SelfViewModel(stockRepository, easyMoneyRepository) as T
            } else {
                throw ClassCastException("这不是我向要的：${modelClass.canonicalName}")
            }
        }

    }
}